<template>
	<div class="recognize">
		<el-form>
			<el-row :gutter="24">
				<el-col :span="6">
					<el-form-item label="模型版本">
						<el-select v-model="from.currentModel"  placeholder="请选择" @change="switchModel">
							<el-option v-for="item in modelList" :key="item" :label="item" :value="item"/>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item :label="`置信度`">
						<div style="display: flex; align-items: center; width: 100%;">
							<el-slider style="flex: 1; margin-right: 1rem;"  v-model="from.confidence" :max="1" :min="0.1" :step="0.01"/>
							<span>{{from.confidence}}</span>
						</div>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>

		<el-row :gutter="24">
			<el-col>
				<el-form-item label="显示类型">
					<el-checkbox-group v-model="from.show_category">
						<el-checkbox
							v-for="item in modelInfos"
							:key="item"
							:label="item"
						>
							{{translate(item)}}
						</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
			</el-col>
		</el-row>

		<el-row :gutter="20" style="margin-top: 20px;">
			<el-col :span="12" style="text-align: center;">
				<el-card style="height: 350px;max-height: 350px;">
					<el-upload
						style="height: 100%;"
						ref="upload"
						:data="uploadFormData"
						class="upload-demo"
						action="/api/image_recognition/uploadImage/"
						:on-success="handleUploadSuccess"
						drag
						:show-file-list="false"
						multiple
						:limit="1"
						:on-exceed="handleExceed"
					>
						<el-icon class="el-icon--upload"><upload-filled /></el-icon>
						<div class="el-upload__text">
							拖拽文件到这 / <em>点击上传</em>
						</div>
					</el-upload>
				</el-card>
			</el-col>
			<el-col :span="12">
				<el-card style="height: 350px;max-height: 350px;">
					<el-descriptions title="最新识别结果" column="2" border direction="vertical" v-if="nowRecord.upload_image">
						<el-descriptions-item label="识别图片" :rowspan="3" align="center">
							<el-image
								v-if="nowRecord"
								class="recordImage"
								:src="'api/'+nowRecord.upload_image"
								fit="cover"
								:preview-src-list="['api/'+nowRecord.upload_image]"
							/>
						</el-descriptions-item>
						<el-descriptions-item label="时间" align="center">{{ formatTime(nowRecord?.time) }}</el-descriptions-item>
						<el-descriptions-item label="置信度" align="center">{{ handleDecimal(Number(nowRecord?.confidence)) }}%</el-descriptions-item>
						<el-descriptions-item label="识别结果" align="center">{{ translate(nowRecord?.result_type) }}</el-descriptions-item>
					</el-descriptions>
					<el-empty description="还没有识别任何图片哦~" v-else/>
				</el-card>
			</el-col>
		</el-row>

		<el-row :gutter="20" style="margin-top: 20px;" v-if="yoloResult.resultTypeCount">
			<el-col :span="12">
				<el-card >
					<hz-echarts-line-base id="line1" ref="line1" style="min-height: 300px;max-height: 300px;"/>
				</el-card>
			</el-col>
			<el-col :span="12">
				<el-card>
					<hz-echarts-pie-base id="pie1" ref="pie1" style="min-height: 300px;max-height: 300px;"/>
				</el-card>
			</el-col>
		</el-row>
		<el-row :gutter="20" style="margin-top: 20px;">
			<el-col :span="24">
				<el-card>
					<el-empty description="暂无记录!"></el-empty>
				</el-card>
			</el-col>
		</el-row>
	</div>
</template>
<script setup lang="ts">

import {useMessage} from "/@hooks/message";
import {ref, reactive, onMounted, computed} from "vue";
import {genFileId, UploadProps, UploadRawFile, ElMessage} from "element-plus";
import {UploadFilled} from "@element-plus/icons-vue";
const globalSubTitle = ref(import.meta.env.VITE_GLOBAL_SUBTITLE?.trim() || 'HZSYSTEM');
const upload = ref(null)
import dayjs from 'dayjs'
import HzEchartsPieBase from '/@/components/echarts/pie/Hz-Echarts-Pie-Base.vue'
import HzEchartsLineBase from '/@/components/echarts/line/Hz-Echarts-Line-Base.vue'
import {translate} from '/@/utils/translate'
import {
	getImageRecognitionStatistics
} from "/@api/image_recognition/hz-system-image-recognition-api";
import {changeModel, modelVersions, yoloModelInfo} from "/@api/yolo_model/hz-system-yolo-model-api";


const nowRecord = ref({});

const parseToPie = (data: any) => {
	return data.map((item: any) => {
		return {
			name: item.result_type,
			value: item.count
		}
	})
}

const parseToLine = (data: any) => {
	const xData: string[] = []
	const yData: number[] = []
	data.forEach((item: any) => {
		xData.push(item.time)
		yData.push(item.count)
	})
	return {
		xData,
		yData
	}
}
const yoloResult = ref({})
const loadYoLoRecognitionStatistics = async () => {
	const response = await getImageRecognitionStatistics();

	pie1.value?.refreshChart({
		title: '识别类型',
		subtext: '识别类型统计',
		yData: parseToPie(response.data?.resultTypeCount || {})
	});
	yoloResult.value = response.data

	const lineData = parseToLine(response.data?.resultTimeCount || {})

	line1.value?.refreshChart({
		title: '识别次数/分钟',
		xData: lineData.xData,
		yData: lineData.yData
	});

};
const pageConfig = ref({
	page: 1,
	pageSize: 10,
	total: 0,
});


const from = reactive({
	currentModel: '',
	confidence: 0.5,
	show_category: []
})

const uploadFormData = computed(() => ({
	currentModel: from.currentModel,
	confidence: from.confidence,
	show_category: from.show_category.join(',')
}))
//获取模型下拉
const modelList = ref([])
const modelInfos = ref([])
const getModelVersions = async () => {
	const res = await modelVersions()
	modelList.value = res.data.model_version
	from.currentModel = modelList.value[0]


	const infoRes = await yoloModelInfo()
	modelInfos.value = Object.values(infoRes.data.supported_classes)
	from.show_category = [...modelInfos.value]
}
getModelVersions()

//切换模型
const switchModel = async (model) => {
	const res = await changeModel(model)

	ElMessage({
		type: res.code == 200 ? 'success' : 'error',
		message: res.msg,
		duration: 2000
	})
}

const handleUploadSuccess = (response: any, file: any, fileList: any) => {
	nowRecord.value = response.data
	useMessage().success('图片识别成功')
	loadYoLoRecognitionStatistics();
}

const handleExceed: UploadProps['onExceed'] = (files) => {
	upload.value!.clearFiles()
	const file = files[0] as UploadRawFile
	file.uid = genFileId()
	upload.value!.handleStart(file)
	// 执行上传
	upload.value!.submit()
}
// 格式化显示时间 2025-03-03T23:39:27.918780 => 2025-03-03 23:39:27
const formatTime = (time: string) => {
	return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}
// 处理小数，保留两位小数 0.9999511241912842 => 0.99
const handleDecimal = (num: number) => {
	// 先*100
	const numStr = (num * 100).toString()
	// 找到小数点的位置
	const index = numStr.indexOf('.')
	// 截取小数点后两位
	return numStr.slice(0, index + 3)
}

const pie1 = ref(null);
const line1 = ref(null);

</script>
<style scoped lang="scss">
.recognize{
	padding: 14px;
}
.upload-demo {
	margin: 30px 0;
}


.recordImage{
	width: 150px;
	height: 150px;
}


.collapse-header {
	display: flex;
	align-items: center;
	gap: 15px;
	padding: 12px 0;
}

.record-time {
	color: #606266;
	font-size: 14px;
}

.badge {
	margin-left: auto;
}

.record-image {
	width: 200px;
	height: 200px;
	border-radius: 6px;
	transition: transform 0.3s;
	cursor: pointer;
}

.record-image:hover {
	transform: scale(1.05);
}

.record-result {
	color: #606266;
	font-size: 24px;
}
</style>
